package com.ql.service.socket;

import com.ql.domain.CementMixing;
import com.ql.utils.DateUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.Socket;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Date;

@Component
public class HandlerThread extends Server implements Runnable {
    private Socket socket;
    boolean write;

    public void setSocket(Socket socket) {
        this.socket = socket;
        try {
            socket.setKeepAlive(true);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        s.add(socket);
        System.out.println("客户端地址：" + socket.getInetAddress());
        new Thread(this).start();
    }

    private int read() {
        BufferedInputStream bufferedInput = null;
        byte[] buffer = new byte[1024];
        try {
            //创建BufferedInputStream 对象
            bufferedInput = new BufferedInputStream(socket.getInputStream());
            int bytesRead = 0;


            //从文件中按字节读取内容，到文件尾部时read方法将返回-1
            while ((bytesRead = bufferedInput.read(buffer)) != -1) {
                //将读取的字节转为字符串对象
                String chunk = new String(buffer, 0, bytesRead);
//                System.out.print(chunk);
                System.out.println(chunk);
                String[] sArr = chunk.split(";");
                String device_type = sArr[0].split(",")[1];
                CementMixing cementMixing = new CementMixing();
                cementMixing.setDevice_type(device_type);
                String device_code = sArr[1].split(",")[1];
                cementMixing.setDevice_code(device_code);
                String[] data = sArr[2].split(",");
                cementMixing.setPile_driver_num(data[1]);
                cementMixing.setStake_mark(data[2]);
                cementMixing.setLongitude(data[3]);
                cementMixing.setLatitude(data[4]);
                cementMixing.setSlope(data[5]);
                String start_ymd = data[6];
                String start_hms = data[7];
                String[] start_ymd_split = start_ymd.split("/");
                StringBuilder sb=new StringBuilder();

                String year = DateUtils.date2String(new Date(), "yyyy/MM/dd hh-mm-ss").split("/")[0];
                sb.append(year).append("/").append(start_ymd_split[1]).append("/").append(start_ymd_split[2]).append(" ").append(start_hms);
                String s1 = sb.toString();
                System.out.println(s1);
                cementMixing.setStart_date(DateUtils.string2Date(s1,"yyyy/MM/dd hh-mm-ss"));
                cementMixing.setPile_driver_state(data[8]);
                cementMixing.setPhase(data[9]);
                cementMixing.setDrill_specification(data[10]);
                cementMixing.setWater_cement_ratio(data[11]);
                cementMixing.setDrilling_depth(data[12]);
                cementMixing.setDrilling_speed(data[13]);
                cementMixing.setElectricity(data[14]);
                cementMixing.setCement_flux(data[15]);
                String end_ymd = data[16];
                String end_hms = data[17];
                String[] end_ymd_split = end_ymd.split("/");

                StringBuilder sb2=new StringBuilder();
                sb2.append(year).append("/").append(end_ymd_split[1]).append("/").append(end_ymd_split[2]).append(" ").append(end_hms);
                cementMixing.setEnd_date(DateUtils.string2Date(sb2.toString(),"yyyy/MM/dd hh-mm-ss"));
                cementMixing.setPile_length(data[18]);
                cementMixing.setAu_aol(data[19]);
                cementMixing.setAu_aoc(data[20]);
                cementMixing.setRih_av(data[21]);
                cementMixing.setTo_drill_av(data[22]);
                cementMixing.setAverage_aol(data[23]);
                cementMixing.setAverage_aoc(data[24]);
                cementMixing.setAverage_current(data[25]);
                cementMixing.setPile_time(data[26]);
                cementMixing.setBottom_pile_aoc(data[27]);
                cementMixing.setBottom_pile_aol(data[28]);
                cementMixing.setEmpty_stir_depth(data[29]);
                save(cementMixing);
                doSomething("asd");
            }

            return 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Socket链接已经结束!!!");
            return 1;
        }
    }

    private void write() {
        DataOutputStream outputStream = null;
        String jsonString = Calendar.getInstance().getTime().toString() + "  " + "123";
        try {
            outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
            outputStream.writeUTF(jsonString);
            outputStream.flush();
            //*outputStream.close();*//*
            System.out.println("发送完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void run() {
        System.out.println("客户端数据已经连接" + "客户端地址：" + socket.getInetAddress().toString());
        //有没有要读的。要读就读一下
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    int read = read();
                    if (read == 1) {
                        break;
                    }
                }
            }
        }).start();
        //有没有要写的。要写的就写一下
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    if (write) {
                        write();
                        write = false;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public void doSomething(String ret) {
        System.out.println(ret);
        write = true;
    }

}

